import requests
import datetime

# 假设这是后台 API 的 URL，你需要替换为实际的 URL
API_URL = "http://127.0.0.1:5000/api/query_dwzb_eta"
# 假设这是提交数据的 API URL
SUBMIT_API_URL = "http://127.0.0.1:5000/api/daily_stats"

def process_api_data():
    
    now = datetime.datetime.now()
    hour = now.hour + now.minute / 60
    today = datetime.datetime.today()
    fnow_time = now.strftime("%Y-%m-%d %H:%M:%S")

    # 编写SQL查询语句
    if hour < 8.5:  # 日期，班次
        today = today - datetime.timedelta(days=1)
        formatted_date = today.strftime("%Y%m%d")
        shift = "N"
    elif hour > 20.5:
        formatted_date = today.strftime("%Y%m%d")
        shift = "N"
    else:
        formatted_date = today.strftime("%Y%m%d")
        shift = "D"

    # 定义产品列表
    products = ["TW210-216C", "HNDG210AT216C1", "TW210-220E"]

    for product in products:
        try:
            form_data = {
                "query_date": formatted_date,
                "shift": shift,
                "product": product
            }
            print(form_data)
            # 发送 POST 请求到 API
            response = requests.post(API_URL, json=form_data)

            # 检查响应状态码
            if response.status_code == 200:
                # 解析 JSON 数据
                data = response.json()
                aggtj_data = data.get('aggtj_data', [])
                sumbin_data = data.get('sumbin_data', [])
                print(aggtj_data)
                if not aggtj_data:  # 检查返回的数据是否为空
                    print(f"产品 {product} 返回的数据为空，跳过当前循环")
                    continue

                # 计算总产量
                total_output = sum(item.get('total_sum_ivgrade', 0) for item in aggtj_data)

                # 计算正常产出
                normal_output = sum(item.get('total_sum_ivgrade', 0) for item in aggtj_data if 'Eta' in item.get('Class', '') and 'Eta Fail' not in item.get('Class', ''))

                # 计算平均效率
                eta_items = [item for item in aggtj_data if 'Eta' in item.get('Class', '')]
                avg_efficiency_numerator = sum(item.get('total_sum_ivgrade', 0) * item.get('etacs', 0) for item in eta_items)
                avg_efficiency = (avg_efficiency_numerator / normal_output) if normal_output else 0

                # 计算入库效率
                valid_eta_items = [item for item in aggtj_data if 'Eta' in item.get('Class', '') and 'Eta Fail' not in item.get('Class', '')]
                def convert_to_float(class_str):
                    cleaned_str = class_str.replace('Eta', '').replace('%', '')
                    try:
                        return float(cleaned_str) if '%' in class_str else float(cleaned_str)
                    except ValueError:
                        return 0

                storage_efficiency_numerator = sum(item.get('total_sum_ivgrade', 0) * convert_to_float(item.get('Class', '')) for item in valid_eta_items)
                storage_efficiency = (storage_efficiency_numerator / normal_output) if normal_output else 0

                # 计算合并档产出
                eta_classes = sorted([item for item in aggtj_data if 'Eta' in item.get('Class', '') and 'Eta Fail' not in item.get('Class', '')], key=lambda x: x.get('Class', ''))
                merge_classes = ['UNG', 'IRev2-B', 'Rsh-B']
                if eta_classes:
                    merge_classes.append(eta_classes[0].get('Class', ''))
                merge_output = sum(item.get('total_sum_ivgrade', 0) for item in aggtj_data if any(cls in item.get('Class', '') for cls in merge_classes))

                # 计算漏电合并档产出
                leak_output = sum(item.get('total_sum_ivgrade', 0) for item in aggtj_data if item.get('Class', '') == 'IRev2-B')

                # 计算漏电失效产出
                leak_fail = sum(item.get('total_sum_ivgrade', 0) for item in aggtj_data if item.get('Class', '') == 'IRev2 Fail')

                # 计算 DLCC 产出
                DLCC = sum(item.get('quantity', 0) for item in sumbin_data if item.get('binn') == 7)

                # 准备提交的数据
                submit_data = {
                    "date": formatted_date,
                    "shift": shift,
                    "BinFileName": product,
                    "sum_IvGrade": total_output,
                    "avg_eta": round(avg_efficiency, 3),
                    "ru_eta": round(storage_efficiency, 3),
                    "hbd": merge_output,
                    "dlcc": DLCC,
                    "IRev2_B": leak_output,
                    "IRev2_Fail": leak_fail
                }

                # 发送 POST 请求提交数据
                submit_response = requests.post(SUBMIT_API_URL, json=submit_data)

                if submit_response.status_code == 200:
                    print(f"产品 {product} 数据提交成功")
                else:
                    print(f"产品 {product} 数据提交失败，状态码: {submit_response.status_code}")
            else:
                print(f"产品 {product} 请求失败，状态码: {response.status_code}")
        except requests.RequestException as e:
            print(f"请求发生错误: {e}")

if __name__ == "__main__":
    process_api_data()
